package com.sk.cardeal.act.home.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.cardeal.R;
import com.sk.cardeal.adapter.CostListAdater;
import com.sk.cardeal.adapter.FixProjectAdapter;
import com.sk.cardeal.app.MyApplication;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.entity.ApplyFormEntity;
import com.sk.cardeal.entity.Brand;
import com.sk.cardeal.entity.BrandListBean;
import com.sk.cardeal.entity.CostType;
import com.sk.cardeal.entity.CustomDetails;
import com.sk.cardeal.entity.Model;
import com.sk.cardeal.entity.OcrInfo;
import com.sk.cardeal.entity.Project;
import com.sk.cardeal.entity.ProjectListBean;
import com.sk.cardeal.entity.RepairOrderDetail;
import com.sk.cardeal.entity.WorkPostion;
import com.sk.cardeal.entity.WorkPostionList;
import com.sk.cardeal.entity.Worker;
import com.sk.cardeal.entity.WorkerListBean;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.FileUtil;
import com.sk.cardeal.utils.MyApplicationLike;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.RecognizeService;
import com.sk.cardeal.utils.SnackUtils;
import com.sk.cardeal.view.IconViewTextView;
import com.sk.cardeal.view.LineMenuView;
import com.sk.cardeal.view.TitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.sk.cardeal.common.Constants.CAR_CARD;
import static com.sk.cardeal.common.Constants.CHOOSE_CAR_TYPE;
import static com.sk.cardeal.common.Constants.CHOOSE_FIX_PEP;
import static com.sk.cardeal.common.Constants.CHOOSE_PROJECT;
import static com.sk.cardeal.common.Constants.CHOOSE_WORK_POSTION;
import static com.sk.cardeal.common.Constants.OTHER_PAY;

/**
 * Created by sk on 2017/12/15.
 */

public class CleanActivity extends BaseActivity implements HandleDataCallBack, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.scan)
    ImageView scan;
    @BindView(R.id.car_num)
    EditText carNum;
    @BindView(R.id.clean_pep)
    LineMenuView cleanPep;
    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.open)
    ImageView open;
    @BindView(R.id.other_pay)
    IconViewTextView otherPay;
    @BindView(R.id.save)
    TextView save;
    @BindView(R.id.apply_form)
    TextView applyForm;
    @BindView(R.id.other_ryc)
    RecyclerView otherRyc;
    @BindView(R.id.project)
    IconViewTextView project;
    @BindView(R.id.project_ryc)
    RecyclerView projectRyc;

    private LoadingDialog loadingDialog;
    private ApplyFormEntity applyFormEntity;
    private String typeId = "";

    private CostListAdater costListAdater;

    private List<CostType> costTypeList = new ArrayList<>();
    private List<RepairOrderDetail> repairOrderDetails = new ArrayList<>();
    private ArrayList<Project> selectProjectList = new ArrayList<>();
    private FixProjectAdapter fixProjectAdapter;


    @Override
    protected int getContentView() {
        return R.layout.activity_clean;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        applyFormEntity = new ApplyFormEntity();
        applyFormEntity.setUserId("1");
        applyFormEntity.setCompanyId("402880eb60d8b87a0160d8bb2c450001");
        applyFormEntity.setIsUpdate(0);
        applyFormEntity.setType(3);
        applyFormEntity.setCode(MyUtils.getRndNumCode());
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        titleView.setMyCallBack(this);


        projectRyc.setLayoutManager(new LinearLayoutManager(mContext));
        fixProjectAdapter = new FixProjectAdapter(R.layout.item_quickly_fix_project, selectProjectList);
        projectRyc.setAdapter(fixProjectAdapter);
        fixProjectAdapter.setOnItemClickListener(this);
        fixProjectAdapter.setOnItemChildClickListener(this);

        otherRyc.setLayoutManager(new LinearLayoutManager(mContext));
        costListAdater = new CostListAdater(R.layout.item_cost, costTypeList);
        otherRyc.setAdapter(costListAdater);
        costListAdater.setOnItemClickListener(this);
        costListAdater.setOnItemChildClickListener(this);

        projectRyc.setHasFixedSize(true);
        projectRyc.setNestedScrollingEnabled(false);

        otherRyc.setHasFixedSize(true);
        otherRyc.setNestedScrollingEnabled(false);

        carNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 7) {
                    if (MyUtils.isCarNumber(s.toString())) {

                        AppApi.customDetails("", s.toString(), CleanActivity.this, 300, CleanActivity.this);

                    } else {
                        SnackUtils.showError(mRootView, "您输入的车牌号，不合法！");
                    }
                }
            }
        });
    }

    @Override
    public void clickTitle(int i) {
        super.clickTitle(i);
        switch (i) {
            case 1:
                finish();
                break;
        }
    }

    @OnClick({R.id.scan, R.id.clean_pep, R.id.close, R.id.open, R.id.other_pay, R.id.save, R.id.apply_form, R.id.project})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.scan:
                if (MyApplicationLike.isHasGotToken()) {
                    Intent scanIntent = new Intent(mContext, CameraActivity.class);
                    scanIntent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                            FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                    scanIntent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                            CameraActivity.CONTENT_TYPE_BANK_CARD);
                    startActivityForResult(scanIntent, CAR_CARD);
                } else {
                    SnackUtils.showError(mRootView, "ocr扫描尚未准备就绪！");
                }
                break;
            case R.id.clean_pep:
                loadingDialog.show();
                AppApi.getCompanyWorker(CleanActivity.this, 2, CleanActivity.this);
                break;
            case R.id.close:
                break;
            case R.id.open:
                break;
            case R.id.other_pay:
                Intent costIntent = new Intent(mContext, NewCostActivity.class);
                startActivityForResult(costIntent, OTHER_PAY);
                break;
            case R.id.save:
                break;
            case R.id.apply_form:
                setData();
                loadingDialog.show();
                AppApi.submitForm(applyFormEntity, CleanActivity.this, 101, CleanActivity.this);
                break;
            case R.id.project:
                loadingDialog.show();
                AppApi.getFixProject(2, CleanActivity.this, 6, CleanActivity.this);
                break;
        }
    }

    private void setData() {

        applyFormEntity.setCarNumber(carNum.getText().toString());

        for (CostType costType : costTypeList) {
            RepairOrderDetail repairOrderDetail = new RepairOrderDetail();
            repairOrderDetail.setType(3);
            repairOrderDetail.setNum(1);
            repairOrderDetail.setOtherName(costType.getCostName());
            repairOrderDetail.setOtherPrice(Double.parseDouble(costType.getPrice()));
            repairOrderDetail.setOtherCost(Double.parseDouble(costType.getCost()));
            repairOrderDetail.setOtherRemark(costType.getRemark());
            repairOrderDetails.add(repairOrderDetail);
        }

        applyFormEntity.setRepairOrderDetail(repairOrderDetails);
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 2:
                WorkerListBean workerListBean = JSON.parseObject(result, WorkerListBean.class);
                ArrayList<Worker> workerArrayList = (ArrayList<Worker>) workerListBean.getResultList();
                Intent workIntent = new Intent(mContext, PepChooseActivity.class);
                workIntent.putParcelableArrayListExtra("data", workerArrayList);
                startActivityForResult(workIntent, CHOOSE_FIX_PEP);
                break;
            case 3:
                WorkPostionList workPostionList = JSON.parseObject(result, WorkPostionList.class);
                ArrayList<WorkPostion> workFormList = (ArrayList<WorkPostion>) workPostionList.getResultList();
                Intent intent = new Intent(mContext, ChooseWorkPostionActivity.class);
                intent.putParcelableArrayListExtra("data", workFormList);
                startActivityForResult(intent, CHOOSE_WORK_POSTION);
                break;
            case 101:
                Toast.makeText(mContext, "洗车单新增成功！", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                finish();
                break;
            case 6:
                ProjectListBean projectListBean = JSON.parseObject(result, ProjectListBean.class);
                ArrayList<Project> projectArrayList = (ArrayList<Project>) projectListBean.getResultList();
                Intent projectIntent = new Intent(mContext, ChooseFixProjectActivity.class);
                projectIntent.putParcelableArrayListExtra("data", projectArrayList);
                projectIntent.putParcelableArrayListExtra("select", selectProjectList);
                projectIntent.putExtra("type", 2);
                startActivityForResult(projectIntent, CHOOSE_PROJECT);
                break;
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case CHOOSE_FIX_PEP:
                    Worker worker = data.getParcelableExtra("worker");
                    cleanPep.setHint(worker.getPersonName());
                    cleanPep.setHintColor(Color.parseColor("#232323"));
                    applyFormEntity.setTechnicianId(worker.getId());
                    break;
                case OTHER_PAY:
                    CostType costType = data.getParcelableExtra("data");
                    costTypeList.add(costType);
                    costListAdater.notifyDataSetChanged();
                    break;
                case CAR_CARD:
                    RecognizeService.recLicensePlate(FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(),
                            new RecognizeService.ServiceListener() {
                                @Override
                                public void onResult(String result, Bitmap bitmap) {
                                    Log.v("recLicensePlate", result);
                                    if (bitmap != null) {
                                        OcrInfo ocrInfo = JSONObject.parseObject(result, OcrInfo.class);
                                        carNum.setText(ocrInfo.getWords_result().getNumber());
                                    } else {
                                        SnackUtils.showError(mRootView, "识别失败，请重试!");
                                    }
                                }
                            });
                    break;
                case CHOOSE_PROJECT:
                    selectProjectList.clear();
                    List<Project> projects = data.getParcelableArrayListExtra("data");
                    selectProjectList.addAll(projects);
                    fixProjectAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter instanceof CostListAdater) {
            switch (view.getId()) {
                case R.id.right:
                    costTypeList.remove(position);
                    costListAdater.notifyDataSetChanged();
                    break;
            }
        }else if(adapter instanceof FixProjectAdapter){
            switch (view.getId()) {
                case R.id.right:
                    selectProjectList.remove(position);
                    fixProjectAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }
}
